import logging
import requests
from urllib.parse import quote

from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from search_main.utlis import TimeUtils
from search_main.utlis import HttpClient
from search_main.utlis import generate_mid

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ViewsWeibo(APIView, TimeUtils):

    def __init__(self):
        super().__init__()
        self.http_client = HttpClient()
        self.time_utils = TimeUtils()


    def get(self, request):

        try:
            response = self.http_client.get_client(settings.API_WEIBO_URL)
            data = response['data']['data']

            processed_data = []

            for i, item in enumerate(data['realtime']):
                key = item['word_scheme'] if 'word_scheme' in item else f"#{item['word']}"
                entry = {
                    "id": generate_mid(),  # 微博热搜唯一标识（微博消息ID）
                    "title": item['word'],  # 热搜关键词（如："#我国成功发射卫星#"）
                    "desc": item.get('note', key),  # 补充说明（可能包含事件描述/话题类型）
                    "author": item.get('flag_desc', ''),  # 分类标签（如："要闻/民生/娱乐"）
                    "timestamp": self.time_utils.get_timestamp(), # 上榜时间（精确到秒）
                    "hot": item['num'],  # 热度数值（反映话题讨论量）
                    "url": f"https://s.weibo.com/weibo?q={quote(key)}&t=31&band_rank=1&Refer=top",  # PC端直达链接
                    "mobileUrl": f"https://s.weibo.com/weibo?q={quote(key)}&t=31&band_rank=1&Refer=top"  # 移动端直达链接
                }
                processed_data.append(entry)

            result = {
                "name": "weibo",
                "title": "微博",
                "type": "热搜榜",
                "description": "实时热点，每分钟更新一次",
                "link": "https://s.weibo.com/top/summary/",
                "total": len(data['realtime']),
                "data": processed_data
            }

            # =================
            print(f"总条数: {result['total']}")
            for index, item in enumerate(processed_data[:10], 1):
                print(f"{index}. {item['title']} - 热度：{item['hot']}")
                print(f"   链接：{item['url']}\n")
            # =================

            return Response(result, status=status.HTTP_200_OK)
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return Response(
                {"error": "服务暂不可用"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )